﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI.HtmlControls;

using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.order
{
    public partial class OrderAdd : BaseAdmin
    {
        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly DALCardType theCardType = new DALCardType();
        readonly Card theCard = new Card();
        readonly dalCar theDalCar = new dalCar();
        readonly Car theCar = new Car();
        List<tbProfessionAreaType> lstProfessionType = new List<tbProfessionAreaType>();
        readonly DALProfessionAreaType theProfessionAreaType = new DALProfessionAreaType();
        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly Order theOrder = new Order();

        public string address = "";
        public string carid = "0";
        public string carinfo = "";
        public string cname = "";
        public string email = "";
        public string istrue = "0";
        public string phone = "";
        public string post = "";
        public string score1 = "0";
        public string score2 = "0";
        public string score3 = "0";
        public string shipmsg = "";
        public string tel = "";
        public string totalprice = "0";
        public string totalscore = "0";

        dbOrder oOrder;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddOrder);

                if (Session["callerid"] != null)
                {
                    string callTel = string.Empty;
                    if (Session["callerid"].ToString().Length == 11)
                    {
                        this.txtPhone.Text = Session["callerid"].ToString();
                        callTel = this.txtPhone.Text;
                    }
                    else
                    {
                        this.txtTel.Text = Session["callerid"].ToString();
                        callTel = this.txtTel.Text;
                    }
                    oOrder = theOrder.GetModelByTel(callTel);
                    if (oOrder != null)
                    {
                        this.txtUserName.Text = oOrder.cname1;
                        string[] sAddress = oOrder.address1.Split(',');
                        if (sAddress.Length == 3)
                        {
                            this.AddressArea1.SetProvence (sAddress[0]);
                            this.AddressArea1.SetArea(sAddress[1]);
                            this.txtAddress.Text = sAddress[2];
                        }
                        else
                        {
                            this.txtAddress.Text = oOrder.address1;
                        }
                    }


                }
                if (Request.QueryString["action"] == "del")
                {
                 
                    this.theOrderAccount.DeleOrderAccount(Request.QueryString["code"], int.Parse(Request.QueryString["id"]));
                    UserCardCodeList.RemoveAll(item => item.UserCardId == Request.QueryString["id"]);
                    base.Response.Write("<script  language='javascript'>alert('删除成功!');</script>");        
                    this.BuildCardInfo();
                    this.lblOrderCode.Text = Request.QueryString["code"];
                    
                }
                else
                {                
                    this.GenerateOrderCode();
                  
                }
                this.txtSendDate.Text = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
            }        

        }



        void GenerateOrderCode()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["orderCode"]))
            {
                this.lblOrderCode.Text = Request.QueryString["orderCode"];
            }
            else
            {
                this.lblOrderCode.Text = theOrderAccount.GenerateOrderCode();
            }
        }
   

   
        protected void ibtnAdd_Click(object sender, ImageClickEventArgs e)
        {
            this.lblCardDescription.Text = string.Empty;
            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
            s.Start();

            if (string.IsNullOrEmpty(this.lblOrderCode.Text.Trim()))
            {
                base.Response.Write("<script  language='javascript'>alert('请添加新订单!');</script>");
                return;
            }
            dbCard oCard;
            oCard = theCard.GetModel(this.txtCardCode.Text.Trim(), this.txtCardPassword.Text.Trim());
            if (oCard != null)
            {
                if (oCard.states == 0)
                {
                    this.lblCardDescription.Text = "该卡还处于未发行状态，不能进行兑换！";
                }
                else if (oCard.states == 2)
                {
                    this.lblCardDescription.Text = "该卡已被使用！";
                }
                else if (oCard.states == 3)
                {
                    this.lblCardDescription.Text = "该卡还处于禁用状态，不能进行兑换！！";
                }
                else if (oCard.states == 4)
                {
                    this.lblCardDescription.Text = "该卡处于已领用未激活状态,请先开卡后才能使用！";
                }
                else if (oCard.StartTime > DateTime.Now.Date)
                {
                    this.lblCardDescription.Text = "该卡还未到兑换时间！";
                }
                else if (oCard.endtime < DateTime.Now.Date)
                {
                    this.lblCardDescription.Text = "该卡已过有效兑换时间！";
                }
                else if (oCard.states == 1)
                {
                    theOrderAccount.AddCardToCardAccount(this.lblOrderCode.Text.Trim(), oCard.cardid);
                    UserCard oUserCard = new UserCard();
                    oUserCard.UserCardId = oCard.cardid.ToString();
                    oUserCard.UserCardCode = oCard.cardcode;
                    oUserCard.UserCardPassword = oCard.cardpas;
                    oUserCard.UserCardPrice = oCard.cardprice.ToString();
                    oUserCard.UserCardTypeId = oCard.cardtypeId.ToString();
                    if (UserCardCodeList == null || !UserCardCodeList.Exists(item => item.UserCardId == oUserCard.UserCardId))
                    {
                        DataTable dtProduct = theOrderAccount.GetProductByCardId(int.Parse(oUserCard.UserCardId)) ;
                        if (dtProduct == null || dtProduct.Rows.Count <=0 )
                        {
                            this.lblCardDescription.Text = "该卡暂没有要兑换的商品！";
                        }else
                        {
                            if (UserCardCodeList == null) UserCardCodeList = new List<UserCard>();
                              UserCardCodeList.Add(oUserCard);
                        }
                    }

                    this.BuildCardInfo();
                    s.Stop();
                }
            }
            else
            {
                this.lblCardDescription.Text = "卡号或密码不正确！";
            }
        }

        void BuildCardInfo()
        {
            StringBuilder sbCardInfo = new StringBuilder();
            DataTable dtProduct = null;
            foreach (UserCard uc in UserCardCodeList)
            {
                dtProduct = theOrderAccount.GetProductByCardId(int.Parse(uc.UserCardId));
                if (dtProduct == null)
                {
                    UserCardCodeList = null;
                    base.Response.Write("<script  language='javascript'>alert('系统异常，请重新添加卡片!');</script>");
                    return;                
                 }
                else
                {
                    sbCardInfo.AppendFormat("卡号:{0},面额:{1},兑换商品:<a href='/cn/products_details.aspx?pid={2}' target='_blank' >{3}</a>,兑换商品数:1份; <a href='OrderAdd.aspx?action=del&id={4}&code={5}'>删除</a><br/>"
                                            , uc.UserCardCode
                                            , uc.UserCardPrice
                                            , dtProduct.Rows[0]["proid"].ToString()
                                            , dtProduct.Rows[0]["proname"].ToString()
                                            , uc.UserCardId
                                            , this.lblOrderCode.Text.Trim()
                                            );
                }
            }
            this.ltCardInfo.Text = sbCardInfo.ToString();
        }


 

        protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
        {
            if (UserCardCodeList == null)
            {
                base.Response.Write("<script  language='javascript'>alert('请选择添加新订单或者选择未完成的订单!');</script>");
                return;
            }
            dbOrder oOrder = new dbOrder();
            dbCar odbCar = new dbCar();
            tbCar oCar = new tbCar();

            decimal dSumCardPrice = 0;

            foreach (UserCard uc in UserCardCodeList)
            {
                dbCard oTmpCard;
                oTmpCard = theCard.GetModel(uc.UserCardCode,uc.UserCardPassword);
               
                if (oTmpCard == null || oTmpCard.states != 1)
                {
                    base.Response.Write( "<script  language='javascript'>alert('卡号(" + uc.UserCardCode + "),此卡已被使用，请删除后，请重新添加!');</script>");
                    return;
                }
                dSumCardPrice = dSumCardPrice + oTmpCard.cardprice;
            }

            if (UserCardCodeList == null || UserCardCodeList.Count <= 0)
            {
                base.Response.Write("<script  language='javascript'>alert('您还没有选取要购买商品!');</script>");
               return;
            }

            foreach (UserCard uc in UserCardCodeList)
            {
               DataTable dtProduct = theOrderAccount.GetProductByCardId(int.Parse(uc.UserCardId));
                if (dtProduct == null || dtProduct.Rows.Count <= 0)
                {
                    this.lblCardDescription.Text = "该卡暂没有要兑换的商品！";
                }
                else
                {
                    oCar = new tbCar();
                    oCar.OrderCode = this.lblOrderCode.Text.Trim();
                    oCar.ProdNumber = 1;
                    oCar.ProdPrice = decimal.Parse(uc.UserCardPrice);
                    oCar.ProductId = int.Parse(dtProduct.Rows[0]["proid"].ToString());
                    oCar.UpdateDate = DateTime.Now;
                    oCar.Conents = string.Empty;
                    theCar.Add(oCar);  
                }
            }

            oOrder.orderid = int.Parse(this.lblOrderCode.Text.Trim());
            oOrder.ordercode = this.lblOrderCode.Text.Trim();
            oOrder.pay = 15;//付款方式为礼品卡
            oOrder.states = 0;
            oOrder.cname = base.AdminUser;
            oOrder.cname1 = this.txtUserName.Text.Trim();
            oOrder.tel1 = this.txtTel.Text.Trim();
            oOrder.phone1 = this.txtPhone.Text.Trim();
            oOrder.post1 = this.txtPost.Text.Trim();
            oOrder.address1 = this.AddressArea1.GetProvenceArea() + this.txtAddress.Text.Trim();
            oOrder.Senddate = this.txtSendDate.Text.Trim() == "" ? DateTime.Now.AddDays(3) : DateTime.Parse(this.txtSendDate.Text.Trim()); 
            oOrder.ordertime = DateTime.Now;
            oOrder.languages = 1;
            oOrder.cardprice = dSumCardPrice;
            oOrder.totalprice = dSumCardPrice.ToString();
            oOrder.content = this.txtRemark.Text.ToString();
            theOrder.Add(oOrder);

            theDalCar.AddTempToReal(this.lblOrderCode.Text.Trim(),oOrder.orderid);
            theOrderAccount.UpdateComplateAccount(this.lblOrderCode.Text.Trim());
            UserCardCodeList = null;
            base.Response.Write("<script  language='javascript'>alert('提交订单成功!请记住订单编号(" + oOrder.ordercode + ")以便查询!');window.location.href='orders.aspx?oid=" + this.lblOrderCode.Text.Trim() + "&flag=2'</script>");

        }




    }
}